package com.dhcc.bpm.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

/**
 * @program: cbus-bpm-boot
 * @ClassName Certutil
 * @description: TODO
 * @author: xiafayu
 * @create: 2022-04-04 10:48:34
 * @Version 1.0.0
 **/
public class CertUtils {
    private static final Logger log = LoggerFactory.getLogger(CertUtils.class);

    /**
     * @Description: 根据路径获取公钥证书秘钥
     * @param cerPath
     * @return
     * @throws Exception
     */
    public static String getPublicKey(String cerPath) throws Exception {
        CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
        try (FileInputStream fis = new FileInputStream(cerPath);) {
            X509Certificate Cert = (X509Certificate) certificatefactory.generateCertificate(fis);
            PublicKey pk = Cert.getPublicKey();
            String publicKey = new BASE64Encoder().encode(pk.getEncoded());
            return publicKey;
        } catch (IOException e) {
            log.error("读取证书异常：", e);
        }
        return null;

    }

    /**
     * @Description: 根据路径获取私钥证书秘钥
     * @param storePath
     * @param storePw
     * @param keyPw
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(String storePath, String storePw, String keyPw) throws Exception {
        try (FileInputStream is = new FileInputStream(storePath);) {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(is, storePw.toCharArray());
            is.close();
            Enumeration enumeration = ks.aliases();
            String alias = null;
            while(enumeration.hasMoreElements()) {
                alias = (String)enumeration.nextElement();
                log.info("alias name: ", alias);
//                Certificate certificate = ks.getCertificate(alias);
//                System.out.println(certificate.toString());
            }

            PrivateKey key = (PrivateKey) ks.getKey(alias, keyPw.toCharArray());
            System.out.println("privateKey:" + new BASE64Encoder().encode(key.getEncoded()));
            String privateKey = new BASE64Encoder().encode(key.getEncoded());
            return privateKey;
        } catch (IOException e) {
            log.error("读取证书异常：", e);
        }
        return null;
    }

}
